package com.example.demo.test.upload;

import org.apache.tomcat.jni.FileInfo;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * @auth
 **/
@RestController
@RequestMapping("/upload")
public class FileController {
    @PostMapping
    public void upload(MultipartFile file) throws IOException {
        System.out.println(file.getName());
        System.out.println(file.getOriginalFilename());
        System.out.println(file.getSize());
        File localFile = new File("D://fileUploadTest.xlsx");
        file.transferTo(localFile);
    }
    @GetMapping("/{id}")
    public void download(@PathVariable String id, HttpServletRequest request, HttpServletResponse response) {
        try (
                FileInputStream inputStream = new FileInputStream(new File("D://test.txt"));
             ServletOutputStream outputStream = response.getOutputStream();
        ) {
            // 声明响应类型
            response.setContentType("application/x-download");
            // 下载的文件名称
            response.addHeader("Content-Disposition", "attachment;filename-test.txt");
            IOUtils.copy(inputStream, outputStream);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
